/*
@Author   : Uyynot
@Email    : uyynot@qq.com
@Time     : 2023/10/18 13:08
@File     : repository.go
@Project  : GoProject
@Desc     :
*/
package repository

import (
	"GoProject/internal/model"
	"GoProject/pkg/log"
	"context"
	"fmt"
	"github.com/redis/go-redis/v9"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

type Repository struct {
	db     *gorm.DB
	rdb    *redis.Client
	logger *log.Logger
}

// NewDB 实例化数据库
func NewDB(conf *viper.Viper) *gorm.DB {
	db, err := gorm.Open(mysql.Open(conf.GetString("mysql.dsn")), &gorm.Config{})
	if err != nil {
		panic(fmt.Sprintf("mysql error: %s", err.Error()))
	}
	db.AutoMigrate(&model.User{})
	return db
}

// NewRedis 实例化redis
func NewRedis(conf *viper.Viper) *redis.Client {
	redisClient := redis.NewClient(&redis.Options{
		Addr:         conf.GetString("redis.addr"),
		Password:     conf.GetString("redis.password"),
		DB:           conf.GetInt("redis.db"),
		ReadTimeout:  conf.GetDuration("redis.read_timeout"),
		WriteTimeout: conf.GetDuration("redis.write_timeout"),
	})
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if _, err := redisClient.Ping(ctx).Result(); err != nil {
		panic(fmt.Sprintf("redis error: %s", err.Error()))
	}
	return redisClient
}

func NewRepository(db *gorm.DB, rdb *redis.Client, logger *log.Logger) *Repository {
	return &Repository{
		db:     db,
		rdb:    rdb,
		logger: logger,
	}
}
